package com.jade.store.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.jade.bss.base.customer.Customer;
import com.jade.bss.db.impl.BaseFacadeImpl;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.Restrictions;
import com.jade.framework.base.util.PagingList;
import com.jade.store.wechat.biz.business.account.QrcodeCreateBusiness;
import com.jade.store.wechat.biz.protocol.account.QrcodeCreatePermanentReq;
import com.jade.store.wechat.biz.protocol.account.QrcodeCreatePermanentRes;
import com.jade.store.wechat.biz.protocol.account.QrcodeCreateTemReq;
import com.jade.store.wechat.biz.protocol.account.QrcodeCreateTemRes;
import com.jade.store.wechat.biz.protocol.account.accountTool.QrcodePerScene;
import com.jade.store.wechat.biz.protocol.account.accountTool.QrcodeScene;
import com.jade.store.wechat.dao.WechatQrcodeDao;
import com.jade.store.wechat.entity.WechatQrcode;
import com.jade.store.wechat.service.WechatQrcodeFacade;
import com.jade.zsy.base.common.ToolMethodUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.Date;

/**
 * 微信二维码
 * User: JinYa 2009_jinya@163.com
 * Date: 2016-5-5
 * Time: 10:53
 * Version : 1.0
 * Remark:
 * History:
 */
@Service("WechatQrcodeFacade")
public class WechatQrcodeFacadeImpl extends BaseFacadeImpl implements WechatQrcodeFacade {
    @Inject
    @Named("WechatQrcodeDao")
    private WechatQrcodeDao wechatQrcodeDao;

    @Transactional(propagation= Propagation.REQUIRED)
    public WechatQrcode getTempWxQrcode(Customer customer, String appid,String secid,int type) throws Exception {
        //获取最新的二维码
        Criteria criteria = new Criteria();
        criteria.add(Restrictions.eq("ownerId", customer.getOwnerId()));
        criteria.add(Restrictions.eq("secid", secid));
        criteria.add(Restrictions.eq("busType", type));
        criteria.add(Restrictions.eq("action_name", WechatQrcode.QR_SCENE));//临时二维码
        criteria.addOrder(com.jade.framework.base.criterion.Order.desc("createTime"));
        PagingList<WechatQrcode> list =  wechatQrcodeDao.queryEntity(WechatQrcode.class,criteria);
        WechatQrcode qrcode=new WechatQrcode();
        if(list==null || list.size()<=0){//首次获取的时候
            qrcode.setBusType(type);
            qrcode.setCreator(customer.getName());
            qrcode.setCreatorId(customer.getId());
            qrcode.setOwnerId(customer.getOwnerId());
            qrcode.setSecid(secid);
            qrcode.setAppid(appid);
            wechatQrcodeDao.save(qrcode);
            WechatQrcode  reqQrcode= this.getWxQrcode(appid,String.valueOf(qrcode.getId()));
            qrcode.setReq_expire_seconds(reqQrcode.getReq_expire_seconds());
            qrcode.setAction_name(reqQrcode.getAction_name());
            qrcode.setSceneStr(reqQrcode.getSceneStr());
            qrcode.setTicket(reqQrcode.getTicket());
            qrcode.setUrl(reqQrcode.getUrl());
            qrcode.setExpire_seconds(reqQrcode.getExpire_seconds());
            wechatQrcodeDao.update(qrcode);
        }else{
            qrcode=list.get(0);
            //验证是否已经过期
            if(compareNowDateTime(qrcode.getCreateTime())>qrcode.getExpire_seconds()){
                qrcode= this.getWxQrcode(appid,secid);
                qrcode.setBusType(type);
                qrcode.setCreator(customer.getName());
                qrcode.setCreatorId(customer.getId());
                qrcode.setSecid(secid);
                qrcode.setAppid(appid);
                qrcode.setOwnerId(customer.getOwnerId());
                wechatQrcodeDao.save(qrcode);
                WechatQrcode  reqQrcode= this.getWxQrcode(appid,String.valueOf(qrcode.getId()));
                qrcode.setReq_expire_seconds(reqQrcode.getReq_expire_seconds());
                qrcode.setAction_name(reqQrcode.getAction_name());
                qrcode.setSceneStr(reqQrcode.getSceneStr());
                qrcode.setTicket(reqQrcode.getTicket());
                qrcode.setUrl(reqQrcode.getUrl());
                qrcode.setExpire_seconds(reqQrcode.getExpire_seconds());
                wechatQrcodeDao.update(qrcode);
            }
        }
        return qrcode;
    }

    private WechatQrcode getWxQrcode(String appid,String secid) throws Exception{
        QrcodeCreateBusiness qrcodeCreateBusiness=new QrcodeCreateBusiness(appid);
        QrcodeCreateTemReq req=new QrcodeCreateTemReq();
        req.setAction_name(WechatQrcode.QR_SCENE);
        req.setExpire_seconds(WechatQrcode.DEFUALT_EXPIRE_SECONDS);
        req.setAction_info(new QrcodeScene(String.valueOf(secid)));
        QrcodeCreateTemRes res=qrcodeCreateBusiness.run(req);
        WechatQrcode qrcode=new WechatQrcode();
        qrcode.setReq_expire_seconds(req.getExpire_seconds());
        qrcode.setAction_name(req.getAction_name());
        qrcode.setSceneStr(JSON.toJSONString(req.getAction_info()));
        qrcode.setTicket(res.getTicket());
        qrcode.setUrl(res.getUrl());
        qrcode.setExpire_seconds(res.getExpire_seconds());
        qrcode.setAppid(appid);
        return qrcode;
    }

    @Transactional(propagation= Propagation.REQUIRED)
    public WechatQrcode getPerWxQrcode(Customer customer, String appid,String secid,int type) throws Exception {
        //获取最新的二维码
        Criteria criteria = new Criteria();
        criteria.add(Restrictions.eq("ownerId", customer.getOwnerId()));
        criteria.add(Restrictions.eq("secid", secid));
        criteria.add(Restrictions.eq("busType", type));
        criteria.add(Restrictions.eq("action_name", WechatQrcode.QR_LIMIT_STR_SCENE));//永久二维码
        criteria.addOrder(com.jade.framework.base.criterion.Order.desc("createTime"));
        PagingList<WechatQrcode> list =  wechatQrcodeDao.queryEntity(WechatQrcode.class,criteria);
        WechatQrcode qrcode=new WechatQrcode();
        if(list==null || list.size()<=0){//首次获取的时候
            qrcode= this.getWxPerQrcode(appid,secid);
            qrcode.setBusType(type);
            qrcode.setCreator(customer.getName());
            qrcode.setCreatorId(customer.getId());
            qrcode.setOwnerId(customer.getOwnerId());
            qrcode.setSecid(secid);
            wechatQrcodeDao.save(qrcode);
        }else{
            qrcode=list.get(0);
            //验证是否已经过期
            if(compareNowDateTime(qrcode.getCreateTime())>qrcode.getExpire_seconds()){
                qrcode= this.getWxPerQrcode(appid, secid);
                qrcode.setBusType(type);
                qrcode.setCreator(customer.getName());
                qrcode.setCreatorId(customer.getId());
                qrcode.setOwnerId(customer.getOwnerId());
                qrcode.setSecid(secid);
                wechatQrcodeDao.save(qrcode);
            }
        }
        return qrcode;
    }

    private WechatQrcode getWxPerQrcode(String appid,String secid) throws Exception{
        QrcodeCreateBusiness qrcodeCreateBusiness=new QrcodeCreateBusiness(appid);
        QrcodeCreatePermanentReq req=new QrcodeCreatePermanentReq();
        req.setAction_name(WechatQrcode.QR_LIMIT_STR_SCENE);
        req.setAction_info(new QrcodePerScene(String.valueOf(secid)));
        QrcodeCreatePermanentRes res=qrcodeCreateBusiness.run(req);
        WechatQrcode qrcode=new WechatQrcode();
        qrcode.setAction_name(req.getAction_name());
        qrcode.setSceneStr(JSON.toJSONString(req.getAction_info()));
        qrcode.setTicket(res.getTicket());
        qrcode.setUrl(res.getUrl());
        qrcode.setAppid(appid);
        return qrcode;
    }
    private long compareNowDateTime(Date fromTiem){
        Date nowDate=new Date();//当前时间
        long nowTime=nowDate.getTime();
        long lastTime=fromTiem.getTime();//以前的时间\r
        long time=nowTime-lastTime;//时间相减比较。
        return time;
    }

   public WechatQrcode getQrcodeByEventKey(String eventKey) throws  Exception{
       Criteria criteria = new Criteria();
       if(ToolMethodUtil.isNumber(eventKey)){
           criteria.add(Restrictions.eq("id", Long.parseLong(eventKey)));
       }else{
           criteria.add(Restrictions.eq("secid", eventKey));
       }
       criteria.addOrder(com.jade.framework.base.criterion.Order.desc("createTime"));
       PagingList<WechatQrcode> list =  wechatQrcodeDao.queryEntity(WechatQrcode.class,criteria);
       if(list!=null && list.size()>0)return list.get(0);
        return null;
    }
}
